import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, ScrollView } from "react-native";
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import Loading from "@/components/LoadingModal";
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import { TransactionStatus } from '@/config/config'
import api from "@/request/api";
import TransferDetail from "./components/transferDetail";
import ConfirmationDetail from "./components/confirmationDetail";
import CommonContext from "@/utils/createContext";
import ButtonContent from "./components/buttonContent";
import { getValue } from "@/utils/deviceStorage";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenSendGeneralDetail = (props) => {

    const dispatch = useDispatch()
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [isSign, setIsSign] = useState(false);       //当前单签地址是否已经签名
    const [isSignFinish, setIsSignFinish] = useState(false);    //当前交易是否已完成
    const [isSignExecute, setIsSignExecute] = useState(false);  //当前交易是否在执行阶段
    const [executor, setExecutor] = useState({});
    const [signAccounts, setSignAccounts] = useState([]);
    const [noSignAccounts, setNoSignAccounts] = useState([]);
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet || {});
    const transcationDetail = useSelector((state) => state.sectokenMainReducer.transcationDetail || {});
    const readOnly = useSelector((state) => state.sectokenMainReducer.readOnly);
    const safeQueueList = useSelector((state) => state.sectokenMainReducer.safeQueueList);

    useEffect(() => {
        let params = props.route.params
        if (params && params.txId) {
            getTranscationDetail(params.txId)
        }
    }, [props])

    const getTranscationDetail = (txId) => {
        //获取交易详情
        setLoadingVisible(true)
        setTimeout(async () => {
            let result = await api.get_transaction_detail(txId)
            if (result && result.txId) {
                let count = 0
                safeQueueList && safeQueueList.forEach((item = {}) => {
                    if (item.transaction?.executionInfo?.nonce == result.detailedExecutionInfo?.nonce) {
                        count++
                    }
                })
                if (count > 1) {
                    //有两条nonce相同的数据，说明有一条为rejection,此时该条数据不可再rejection
                    result.isRejection = true
                }
                dispatch({ type: "setTranscationDetail", value: { ...result } });
                //获取交易状态，分开处理
                //获取合约钱包的ownerList
                let list = selectedSafeWallet?.ownerList
                let data = getValue('selectedWallet')
                let signs = []
                let noSigns = []
                switch (result.txStatus) {
                    case TransactionStatus.AWAITING_CONFIRMATIONS:
                        setIsSignExecute(false)
                        setIsSignFinish(false)
                        list && list.forEach(item => {
                            let label = true
                            result.detailedExecutionInfo.confirmations.forEach(item1 => {
                                if (item1.signer.value?.toLowerCase() === item.address?.toLowerCase()) {
                                    label = false
                                    signs.push(item)
                                }
                                if (item1.signer.value?.toLowerCase() === data.address?.toLowerCase()) {
                                    setIsSign(true)
                                }
                            })
                            if (label) {
                                noSigns.push(item)
                            }
                        });
                        setSignAccounts(signs)
                        setNoSignAccounts(noSigns)
                        break;
                    case TransactionStatus.AWAITING_EXECUTION:
                        setIsSignExecute(true)
                        setIsSignFinish(false)
                        setSignAccounts(list)
                        setIsSign(true)
                        setSignAccounts(list)
                        break;
                    case TransactionStatus.CANCELLED:
                        //暂不清楚如何处理
                        break;
                    case TransactionStatus.FAILED:
                        //暂不清楚如何处理
                        break;
                    case TransactionStatus.PENDING:
                        //暂不清楚如何处理
                        break;
                    case TransactionStatus.SUCCESS:
                        setIsSignExecute(true)
                        setIsSignFinish(true)
                        let obj = {
                            address: result.detailedExecutionInfo.executor?.value,
                            label: '',
                            profile: 'profile_logo3'
                        }
                        list && list.forEach(item => {
                            if (item.address?.toLowerCase() === result.detailedExecutionInfo.executor?.value?.toLowerCase()) {
                                obj = item
                            }
                        })
                        setExecutor(obj)
                        setIsSign(true)
                        setSignAccounts(list)
                        break;
                    case TransactionStatus.WILL_BE_REPLACED:
                        //暂不清楚如何处理
                        break;
                    default:
                        break;
                }
            }
            setLoadingVisible(false)
        }, 100);
    }

    const handlePressLeft = () => {
        let params = props.route.params
        if (params && params.source === 'send-result') {
            props.navigation.navigate('safe-main')
        } else {
            props.navigation.goBack()
        }
    }

    const handlePressReject = () => {
        props.navigation.navigate({
            name: 'safe-send-owner',
            params: {
                source: 'rejection'
            }
        })
    }

    const handlePressConfirm = () => {
        props.navigation.navigate('safe-send-owner')
    }

    const handlePressExecute = () => {
        props.navigation.navigate('safe-send-execute')
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenCommonCenterProps} {...{ title: 'Transaction Details' }} handlePressLeft={handlePressLeft} />
            <ScrollView style={styles.bodyContent}>
                <CommonContext.Provider value={{ transcationDetail, isSignFinish }}>
                    <TransferDetail />
                </CommonContext.Provider>
                <CommonContext.Provider value={{ transcationDetail, isSignFinish, isSign, signAccounts, noSignAccounts, executor }}>
                    <ConfirmationDetail />
                </CommonContext.Provider>
                {!readOnly && <CommonContext.Provider value={{ transcationDetail, isSignFinish, isSignExecute, isSign, handlePressReject, handlePressConfirm, handlePressExecute }}>
                    <ButtonContent />
                </CommonContext.Provider>}
            </ScrollView >
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    bodyContent: {
        flex: 1,
        marginTop: 11 * ratio
    }
})
export default SectokenSendGeneralDetail